package com.oneandone.httpserver.tcp;

import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;

import com.oneandone.httpserver.tcp.http.BasicHttpHandler;

/**
 * @author calin
 */
public class BasicTcpConnectionHandler implements TcpConnectionHandler {
	private static final Logger LOGGER = Logger.getLogger(BasicTcpConnectionHandler.class);
	private ExecutorService executor;
	private BasicHttpHandler httpHandler;
	
	public BasicTcpConnectionHandler(BasicHttpHandler handler, int nrWorkers){
		executor = Executors.newFixedThreadPool(nrWorkers);
		httpHandler = handler;
	}
	
	@Override
	public void shutdown() {
		LOGGER.debug("Connection handler shutting down");
		executor.shutdown();
	}

	@Override
	public void handle(Socket socket) {
		executor.execute(new ConnectionWorker(socket));
	}

	private class ConnectionWorker implements Runnable {
		Socket socket;

		public ConnectionWorker(Socket socket) {
			super();
			this.socket = socket;
		}

		@Override
		public void run() {
			try {
				LOGGER.debug("Started HTTP handler thread");
				httpHandler.handle(socket.getInputStream(),
						socket.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}
